package com.h2View.controller;

import com.h2View.entity.DataType;
import com.h2View.exception.ServiceException;
import com.h2View.utils.MybatisConfigUtil;
import com.h2View.utils.MybatisUtils;
import com.h2View.utils.PropUtil;
import com.h2View.utils.StringUtil;
import com.h2View.utils.ToolUtil;
import com.xjw.annotation.FXController;
import com.xjw.annotation.FXRedirect;
import com.xjw.annotation.FXWindow;
import com.xjw.entity.FXBaseController;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import javafx.beans.value.ChangeListener;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.text.Text;

import org.apache.ibatis.io.Resources;

import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.ResourceBundle;

/**
 * @author 徐军文
 * @since 2021/8/21 10:19
 */
@FXController(path = "fxml/login.fxml")
@FXWindow(mainStage = true, title = "登录", icon = "image/icon.png")
public class LoginController extends FXBaseController implements Initializable {

    @FXML
    private TextField urlEle;
    @FXML
    private TextField userNameEle;
    @FXML
    private TextField pwdEle;

    @FXML
    private Text msgEle;

    public static DataType dataType;

    @FXML
    private ComboBox<String> dataTypeEle;

    private ObservableList<String> dataTypeList = FXCollections.observableArrayList();

    private ObservableList<String> userDataList = FXCollections.observableArrayList();

    /**
     * jdbc是否可用
     */
    private static boolean flag = false;


    private Log log = LogFactory.get();

    private Map<String,String> dbInfo;

    private MybatisConfigUtil mybatisConfigUtil;
    {
        try{
            String configPath = "config/mybatis-config.xml";
            File configFile = new File(configPath);
            if(!configFile.exists()){
                if(!configFile.getParentFile().exists()){
                    if(!configFile.getParentFile().mkdirs()){
                        throw new ServiceException(configPath+"父目录创建失败");
                    }
                }
                if(configFile.createNewFile()){
                    InputStream resourceFile = Resources.getResourceAsStream("mybatis-config.xml");
                    FileUtil.writeFromStream(resourceFile,configFile.getAbsolutePath());
                }else{
                    log.error(configPath+"创建失败");
                }
            }
            mybatisConfigUtil = MybatisConfigUtil.newInstance(configFile.getAbsolutePath());
            dbInfo = mybatisConfigUtil.getDbInfo(true);
        }catch (Exception e){
            log.error(e);
        }
    }


    @FXML
    private void testConnect(){
        flag = false;
        String url = urlEle.getText();
        String userName = userNameEle.getText();
        String pwd = pwdEle.getText();
        String dataTypeMsg = dataTypeEle.getSelectionModel().getSelectedItem();
        if(StringUtil.isEmpty(url)){
            setMsg("url不能为空");
            return;
        }
        if(StringUtil.isEmpty(userName)){
            setMsg("userName不能为空");
            return;
        }
        if(StringUtil.isEmpty(dataTypeMsg)){
            setMsg("数据库类型不能为空");
            return;
        }
        dataType = DataType.getDataType(dataTypeMsg);
        dbInfo.put("url",url);
        dbInfo.put("username",userName);
        dbInfo.put("password",pwd);
        dbInfo.put("driver",dataType.getDriver());

        PropUtil.setProperty(dataType.getDataMsg() + "url",url);
        PropUtil.setProperty(dataType.getDataMsg() + "username",userName);
        PropUtil.setProperty(dataType.getDataMsg() + "password",pwd);

        setMsg("正在校验");
        ThreadUtil.execAsync(()->{
            mybatisConfigUtil.setDbInfo(dbInfo);
            mybatisConfigUtil.save();
            PropUtil.store();
            if(MybatisUtils.reLoadResource(mybatisConfigUtil.getFilePath())){
                flag = true;
                setMsg("连接成功");
            }else {
                setMsg("连接失败");
            }
        });
    }

    @FXML
    private void toFunction(){
        ToolUtil.execAsync(this::jumpFunction);
    }


    @FXRedirect
    public String jumpFunction(){
        if(flag){
            return "FunctionController";
        }else{
            if(MybatisUtils.testConnect()){
                flag = true;
                return "FunctionController";
            }else{
                setMsg("当前连接设置不可用！");
                return "LoginController";
            }
        }
    }

    private void setMsg(String msg){
        if(!com.h2View.utils.StringUtil.isEmpty(msg)){
            msgEle.setText(msg);
        }
    }

    private void setTextFildMsg(String value, TextField textFild){
        if(!StringUtil.isEmpty(value)){
            textFild.setText(value);
        }else{
            textFild.setText("");
        }

    }


    @SuppressWarnings("unchecked")
    @Override
    public void initialize(URL location, ResourceBundle resources) {
        String key = DataType.H2.getDataMsg();
        dataTypeList.addAll(DataType.getAllDataMsg());
        dataTypeEle.setItems(dataTypeList);
        dataTypeEle.setValue(DataType.H2.getDataMsg());

        setTextFildMsg(PropUtil.getStr(key + "username"),userNameEle);
        setTextFildMsg(PropUtil.getStr(key + "password"),pwdEle);
        setTextFildMsg(PropUtil.getStr(key + "url"),urlEle);
        ToolUtil.execAsync(this::testConnect);
        dataTypeEle.getSelectionModel().selectedItemProperty().addListener(
            (ChangeListener) (observable, oldValue, newValue) -> changeDataType());
    }

    private void changeDataType(){
        String key = dataTypeEle.getSelectionModel().getSelectedItem();
        setTextFildMsg(PropUtil.getStr(key + "username"),userNameEle);
        setTextFildMsg(PropUtil.getStr(key + "password"),pwdEle);
        setTextFildMsg(PropUtil.getStr(key + "url"),urlEle);
    }


}
